﻿/*
--------------------------------------
File: RotateLicensePlate.cs
Project: Themaopdracht 7
Author: Maarten Kroon

Description:
Finds the angle and rotates the license plate
--------------------------------------
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace THO7_Team8
{
    class RotateLicensePlate : ColorInterface
    {
        public System.Drawing.Bitmap DoAlgorithm(System.Drawing.Bitmap sourceImage)
        {
            //create a new empty bitmap to hold rotated image
            Bitmap returnBitmap = new Bitmap(sourceImage.Width, sourceImage.Height);
            //make a graphics object from the empty bitmap
            Graphics g = Graphics.FromImage(returnBitmap);
            //move rotation point to center of image
            g.TranslateTransform((float)sourceImage.Width / 2, (float)sourceImage.Height / 2);
            //rotate
            g.RotateTransform((float)findAngle(sourceImage));
            //move image back
            g.TranslateTransform(-(float)sourceImage.Width / 2, -(float)sourceImage.Height / 2);
            //draw passed in image onto graphics object
            g.DrawImage(sourceImage, new Point(0, 0));

            //Makes the Bitmap monochrome again to prevent the smoothing of the image
            returnBitmap = MyImage.makeMonochrome(returnBitmap);
            return returnBitmap;
        }

        //Finds the angle that the license plate needs to rotate
        public double findAngle(Bitmap image)
        {
            int width = image.Width;
            int[] array = MyImage.BmpToArray(image);
            int overstaand = 0;

            //Checks the first non black pixel from the left top corner
            int leftCorner = 0;
            while (array[leftCorner] == BLACK)
            {
                leftCorner += width;
            }    
            //Checks the first non black pixel from the right top corner
            int rightCorner = width - 1;
            while (array[rightCorner] == BLACK)
            {
                rightCorner += width;
            }

            //If the image is rotated to the left
            if (leftCorner > rightCorner)
            {
                overstaand = leftCorner;
                double douOverstaand = (double)overstaand / width;
                double angle = Math.Atan(douOverstaand / width);

                angle = angle * (180.0 / Math.PI);

                return angle;
            }
            else if (rightCorner > leftCorner)
            {
                overstaand = rightCorner;
                double douOverstaand = (double)overstaand / width;
                double angle = Math.Atan(douOverstaand / width);

                angle = angle * (180.0 / Math.PI);

                return 0 - angle;
            }
            return 0;
        }
    }
}
